<?php
// app/Controller/UsersController.php
class AdminController extends AppController
{

    var $uses = array('User', 'Group', 'Menu', 'MenuGroup', 'Company','Config','Country','CountryOperator','Faq');

    # Set the layout to use
    var $layout = 'admin_layout';

    public function beforeFilter($param_array = null)
    {
        parent::beforeFilter();
    }

    public function index()
    {
        $this->redirect('users');
    }


    function users($type = 'get')
    {
        $permissions = $this->action_permission;
        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;
            $auth_user = $this->Session->read('loginData');
            switch ($type) {
                case 'get' :
                    /**  Get posted data */
                    $page = isset($_POST['page']) ? $_POST['page'] : 1;
                    /** The current page */
                    $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
                    /** Sort column */
                    $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
                    /** Sort order */
                    $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
                    /** Search column */
                    $search_query = isset($_POST['query']) ? $_POST['query'] : '';
                    /** Search string */
                    $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
                    $limit = $rp;
                    $start = ($page - 1) * $rp;

                    //get users id for this company only

                    $condition_array = array(
                        'User.deleted' => 'n',
                        'User.hidden' => '0'

                    );

                    if (!empty($search_query)) {
                        if ($qtype == 'username') {
                            $condition_array = array(
                                'User.username' => $search_query,
                                'User.deleted' => 'n',
                                'User.hidden' => '0'
                            );
                        } else {
                            $condition_array = array(
                                "User.$qtype LIKE" => $search_query . '%',
                                'User.deleted' => 'n',
                                'User.hidden' => '0'
                            );
                        }
                    }
                    $fields = array('User.id','User.fname','User.mname','User.lname','User.username','User.group_id','User.credit_bal','User.active');
                    $contain = array('Group'=>array('fields'=>array('Group.id','Group.name')));
                    $data_table = $this->User->find('all', array('fields'=>$fields,'conditions' => $condition_array, 'contain' => $contain, 'order' => "User.$sortname $sortorder", 'limit' => $start . ',' . $limit, 'recursive' => 1));
                    $data_table_count = $this->User->find('count', array('conditions' => $condition_array, 'recursive' => -1));

                    $total_records = $data_table_count;

                    if ($data_table) {
                        $return_arr = array();
                        foreach ($data_table as $obj) {
                            $return_arr[] = array(
                                'id' => $obj['User']['id'],
                                'cell' => array(
                                    $obj['User']['id'],
                                    $obj['User']['fname'],
                                    $obj['User']['mname'],
                                    $obj['User']['lname'],
                                    $obj['User']['username'],
                                    $obj['Group']['name'],
                                    $this->formatNumber($obj['User']['credit_bal'], 'money', 2),
                                    $obj['User']['active']
                                )
                            );
                        }
                        return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
                    } else {
                        return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
                    }
                    break;

                case 'save' :
                    if ($_POST['id'] == 0) { //Mew
                        if (!in_array('A', $permissions)) {
                            return json_encode(array('code' => 1, 'msg' => 'Access Denied.'));
                        }
                    } else {
                        if (!in_array('E', $permissions)) {
                            return json_encode(array('code' => 1, 'msg' => 'Access Denied.'));
                        }
                    }

                    if ($_POST['id'] == 0) {
                        //check if username does not exist for in this company
                        $username = $_POST['username'];
                        $res = $this->_validateUsername($username);
                        if ($res) {
                            return json_encode(array('code' => 1, 'msg' => 'Username already exist.'));
                        }
                    }
                    $data = array('User' => $_POST);
                    $pass = '';
                    if ($_POST['id'] == 0) {
                        $pass = $this->randomPassString(6);
                        $data['User']['password'] = AuthComponent::password($pass);
                    }

                    if ($_POST['id'] > 0) {
                        $data['User']['modified_by'] = $auth_user['id'];
                    } else {
                        $data['User']['created_by'] = $auth_user['id'];
                    }

                    if ($this->User->save($this->sanitize($data['User']))) {
                        if ($_POST['id'] > 0) {
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved'));
                        } else { //If new pass back extra data if needed.
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved!  The default password is ' . $pass, 'id' => $this->User->id));
                        }
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Some errors occurred.'));
                    }
                    break;

                case 'reset_password':
                    if (!in_array('E', $permissions)) {
                        return json_encode(array('code' => 1, 'msg' => 'Access Denied.'));
                    }
                    $data = array(
                        'id' => $_POST['id'],
                        'password' => AuthComponent::password(trim($_POST['password']))
                    );
                    if ($this->User->save($this->sanitize($data))) {
                        return json_encode(array('code' => 0, 'msg' => 'Password has been reset.'));
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Password could not be reset.'));
                    }

                    break;

                case 'delete':
                    $ids = $_POST['ids'];
                    $modObj = ClassRegistry::init('User');
                    $result = $modObj->updateAll(
                        array('User.deleted' => "'y'"),
                        array('User.id' => $ids)
                    );
                    if ($result) {
                        echo json_encode(array('code' => 0, 'msg' => 'Data Deleted!'));
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Data cannot be deleted'));
                    }
                    break;


                case 'credit_update':
                    if (!in_array('E', $permissions)) {
                        return json_encode(array('code' => 1, 'msg' => 'Access Denied.'));
                    }
                    $post = $this->sanitize($_POST);

                    $credit_action = $post['credit_action'];
                    $user_id = $post['id'];
                    $amount = trim($post['credit_bal']);
                    if($credit_action =='credit'){
                       $res =  $this->User->addCredit($user_id,$amount);
                    }
                    else{//debit
                        $res =  $this->User->debitCredit($user_id,$amount);
                    }

                    if ($res) {
                        return json_encode(array('code' => 0, 'msg' => 'Credit balance updated!'));
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Failed to update credit balance.'));
                    }

                    break;
            }
        }


        $group_data = $this->Group->getGroups();
        $group_options = $group_data;

        $active = array(
            array('id' => 'Active', 'name' => 'Active'),
            array('id' => 'Disabled', 'name' => 'Disabled')
        );

        $page_title = 'Manage Users';
        $page_summary = 'Manage your users information';
        $page_icon = ' iconfa-user-md';

        $this->set(compact('page_title', 'page_summary', 'page_icon', 'group_options', 'active', 'permissions'));
    }


    function _validateUsername($username = null)
    {
        $data = $this->User->getUserByLoginName($username);
        if ($data) {
            return true;
        } else {
            return false;
        }
    }


    function randomPassString($length)
    {
        return $this->randomString($length);
    }


    function groups($type = 'get')
    {
        $permissions = $this->action_permission;
        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;
            $authUser = $this->Auth->user();

            switch ($type) {
                case 'get' :
                    /**  Get posted data */
                    $page = isset($_POST['page']) ? $_POST['page'] : 1;
                    /** The current page */
                    $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
                    /** Sort column */
                    $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
                    /** Sort order */
                    $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
                    /** Search column */
                    $search_query = isset($_POST['query']) ? $_POST['query'] : '';
                    /** Search string */
                    $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
                    $limit = $rp;
                    $start = ($page - 1) * $rp;


                    $condition_array = array('Group.deleted' => 'n', 'Group.hidden' => '0');

                    if (!empty($search_query)) {
                        if ($qtype == 'name') {
                            /*$condition_array = array(
                                'User.username' => $search_query,
                                'User.deleted' => 'n'
                            );*/
                        } else {
                            /* $condition_array = array(
                                 "User.$qtype LIKE" => $search_query . '%',
                                 'User.deleted' => 'n'
                             );*/
                        }
                    }
                    // $fields = array('User.id', 'User.username', 'User.first_name', 'User.last_name', 'User.group_id', 'User.active');
                    $data_table = $this->Group->find('all', array('conditions' => $condition_array, 'order' => "Group.$sortname $sortorder", 'limit' => $start . ',' . $limit, 'recursive' => -1));
                    $data_table_count = $this->Group->find('count', array('conditions' => $condition_array, 'recursive' => -1));

                    $total_records = $data_table_count;

                    if ($data_table) {
                        $return_arr = array();
                        foreach ($data_table as $obj) {
                            $return_arr[] = array(
                                'id' => $obj['Group']['id'],
                                'cell' => array(
                                    $obj['Group']['id'],
                                    $obj['Group']['name']
                                )
                            );
                        }
                        return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
                    } else {
                        return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
                    }

                    break;

                case 'save' :
                    if ($_POST['id'] == 0) { //Mew
                        if (!in_array('A', $permissions)) {
                            return json_encode(array('code' => 1, 'msg' => 'Access Denied.'));
                        }
                    } else {
                        if (!in_array('E', $permissions)) {
                            return json_encode(array('code' => 1, 'msg' => 'Access Denied.'));
                        }
                    }
                    $data = array('Group' => $_POST);
                    $data['Group']['modified_by'] = $this->Auth->user('id');
                    if ($_POST['id'] == 0) {
                        $data['Group']['created_by'] = $this->Auth->user('id');
                    }

                    if ($this->Group->save($this->sanitize($data))) {
                        if ($_POST['id'] > 0) {
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved'));
                        } else { //If new pass back extra data if needed.
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved.', 'id' => $this->Group->id));
                        }
                        //echo json_encode(array('success' => 0, 'msg' => 'Data Saved!', 'data' => $dt));
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Some errors occurred.'));
                    }

                    break;

                case 'delete':
                    $ids = $_POST['ids'];
                    $modObj = ClassRegistry::init('Group');
                    $result = $modObj->updateAll(
                        $this->sanitize(array('Group.deleted' => "'y'")),
                        $this->sanitize(array('Group.id' => $ids))
                    );
                    if ($result) {
                        echo json_encode(array('code' => 0, 'msg' => 'Data Deleted!'));
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Data cannot be deleted'));
                    }
                    break;
            }
        }

        $page_title = 'Manage User Group';
        $page_summary = 'Manage your users group setup';
        $page_icon = 'iconfa-group';

        $controller = $this;
        $this->set(compact('page_title', 'page_summary', 'page_icon', 'controller', 'permissions'));

    }


    function access_control($group_id = null)
    {
        $authUser = $this->Auth->user();
        $company_profile = $this->global_company;
        $permissions = $this->action_permission;

        if ($this->request->is('post')) {
            $data = $this->request->data['AccessControl'];

            if (!in_array('E', $permissions)) {
                $this->Session->setFlash("Sorry, Access Denied.");
                $this->Session->write('process_error', 'yes');
                $this->redirect(array('action' => 'access_control/' . $data['group_id']));
            }

            $save_new = array();
            foreach ($data['d'] as $acd) {
                if ($acd['menu_id'] > 0) {
                    $perm = array();
                    if (isset($acd['add']) && $acd['add'] == 'A') {
                        $perm[] = $acd['add'];
                    }
                    if (isset($acd['edit']) && $acd['edit'] == 'E') {
                        $perm[] = $acd['edit'];
                    }
                    if (isset($acd['print_export']) && $acd['print_export'] == 'PX') {
                        $perm[] = $acd['print_export'];
                    }
                    if (isset($acd['delete']) && $acd['delete'] == 'D') {
                        $perm[] = $acd['delete'];
                    }
                    $p = implode(',', $perm);
                    $save_new[] = array(
                        'id' => '',
                        'menu_id' => $acd['menu_id'],
                        'group_id' => $data['group_id'],
                        'permission' => $p,
                        'created_by' => $authUser['id'],
                        'modified_by' => $authUser['id']
                    );
                }
            }

            //first delete the existing menu records for this group
            $this->MenuGroup->deleteAll(array('MenuGroup.group_id' => $data['group_id']), false);
            $res = $this->MenuGroup->saveAll($this->sanitize($save_new));
            if ($res) {
                $this->Session->setFlash('Access Control Setup Has been saved !');
                $this->Session->write('process_error', 'no');
            } else {
                $this->Session->setFlash("Sorry, can't save Access Control Setup.");
                $this->Session->write('process_error', 'yes');
            }

            $this->redirect(array('action' => 'access_control/' . $data['group_id']));

        }

        $group_data = $this->Group->getGroups();
        $group_options = array();
        foreach ($group_data as $g) {
            $group_options[$g['id']] = $g['name'];
        }
        $gp = $group_data;
        $group = $group_id;
        $first_group = array_shift($gp);
        if ($group == null) {
            $group = $first_group['id'];
        }
        $menu_data = $this->Menu->getMenusToAssign();
        $group_menu_data = $this->MenuGroup->getGroupMenusIds($group);
        $group_menu_ids = array_keys($group_menu_data);

        $page_title = 'Access Control';
        $page_summary = 'Menus Access and Permissions';
        $page_icon = 'iconfa-key';

        $controller = $this;
        $this->set(compact('page_title', 'page_summary', 'page_icon', 'controller', 'group_options', 'menu_data', 'group_menu_ids', 'group', 'group_menu_data', 'permissions'));
    }


    function company()
    {
        $permissions = $this->action_permission;
        if ($this->request->is('post')) {
            if (!empty($permissions) && !in_array('E', $permissions)) {
                $this->Session->setFlash("Sorry, Access Denied.");
                $this->Session->write('process_error', 'yes');
                $this->redirect(array('action' => 'company'));
            }
            $res = $this->Company->save($this->sanitize($this->request->data));
            if ($res) {
                //$this->Session->write('CompanyProfile', $bdc['Bdc']);
                $this->Session->setFlash('Company profile info has been updated !');
                $this->Session->write('process_error', 'no');
                //return json_encode(array('success'=>0,'msg'=>'Data Saved!','data'=>array('default_pass'=>$omc['Omc']['default_admin_pass'],'name'=>$omc['Omc']['name'],'username'=>$omc['Omc']['default_admin_username'])));
            } else {
                //return json_encode(array('success'=>1,'msg'=>'Some errors occured.'));
                $this->Session->setFlash('Sorry, Company profile info could not be updated');
                $this->Session->write('process_error', 'yes');
            }

            $this->redirect(array('action' => 'company'));
        }

        $company = $this->Company->find('first', array(
            'recursive' => -1
        ));
        $company = $company['Company'];

        $page_title = 'Company Information';
        $page_summary = 'Setup Company Information';
        $page_icon = 'iconfa-sitemap';

        $controller = $this;
        $this->set(compact('page_title', 'page_summary', 'page_icon', 'controller', 'company', 'permissions'));
    }


    function config()
    {
        $permissions = $this->action_permission;
        if ($this->request->is('post')) {
            if (!empty($permissions) && !in_array('E', $permissions)) {
                $this->Session->setFlash("Sorry, Access Denied.");
                $this->Session->write('process_error', 'yes');
                $this->redirect(array('action' => 'config'));
            }
            $res = $this->Config->saveAll($this->sanitize($this->request->data['Config']));
            if ($res) {
                //$this->Session->write('CompanyProfile', $bdc['Bdc']);
                $this->Session->setFlash('Configurations has been updated !');
                $this->Session->write('process_error', 'no');
                //return json_encode(array('success'=>0,'msg'=>'Data Saved!','data'=>array('default_pass'=>$omc['Omc']['default_admin_pass'],'name'=>$omc['Omc']['name'],'username'=>$omc['Omc']['default_admin_username'])));
            } else {
                //return json_encode(array('success'=>1,'msg'=>'Some errors occured.'));
                $this->Session->setFlash('Sorry, Configurations could not be updated');
                $this->Session->write('process_error', 'yes');
            }

            $this->redirect(array('action' => 'config'));
        }

        $configs = $this->Config->getConfigs();

        $page_title = 'Configurations';
        $page_summary = 'Setup Configurations';
        $page_icon = 'iconfa-cog';

        $controller = $this;
        $this->set(compact('page_title', 'page_summary', 'page_icon', 'controller', 'configs', 'permissions'));
    }


    function supported_countries($type = 'get')
    {
        $permissions = $this->action_permission;
        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;
            $authUser = $this->Auth->user();
            switch ($type) {
                case 'get' :
                    /**  Get posted data */
                    $page = isset($_POST['page']) ? $_POST['page'] : 1;
                    /** The current page */
                    $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
                    /** Sort column */
                    $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
                    /** Sort order */
                    $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
                    /** Search column */
                    $search_query = isset($_POST['query']) ? $_POST['query'] : '';
                    /** Search string */
                    $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
                    $limit = $rp;
                    $start = ($page - 1) * $rp;

                    $condition_array = array('Country.deleted' => 'n');

                    if (!empty($search_query)) {
                        if ($qtype == 'name') {
                            $condition_array['Country.name LIKE'] = $search_query . '%';
                        } else {
                            /* $condition_array = array(
                                 "User.$qtype LIKE" => $search_query . '%',
                                 'User.deleted' => 'n'
                             );*/
                        }
                    }
                    // $fields = array('User.id', 'User.username', 'User.first_name', 'User.last_name', 'User.group_id', 'User.active');
                    $data_table = $this->Country->find('all', array('conditions' => $condition_array, 'order' => "Country.$sortname $sortorder", 'limit' => $start . ',' . $limit, 'recursive' => -1));
                    $data_table_count = $this->Country->find('count', array('conditions' => $condition_array, 'recursive' => -1));

                    $total_records = $data_table_count;

                    if ($data_table) {
                        $return_arr = array();
                        foreach ($data_table as $obj) {
                            $return_arr[] = array(
                                'id' => $obj['Country']['id'],
                                'cell' => array(
                                    $obj['Country']['id'],
                                    $obj['Country']['name']
                                )
                            );
                        }
                        return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
                    } else {
                        return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
                    }

                    break;

                case 'save' :
                    if ($_POST['id'] == 0) { //Mew
                        if (!in_array('A', $permissions)) {
                            return json_encode(array('code' => 1, 'msg' => 'Access Denied.'));
                        }
                    } else {
                        if (!in_array('E', $permissions)) {
                            return json_encode(array('code' => 1, 'msg' => 'Access Denied.'));
                        }
                    }
                    $data = array('Country' => $_POST);
                    $data['Country']['modified_by'] = $this->Auth->user('id');
                    if ($_POST['id'] == 0) {
                        $data['Country']['created_by'] = $this->Auth->user('id');
                    }

                    if ($this->Country->save($this->sanitize($data))) {
                        if ($_POST['id'] > 0) {
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved'));
                        } else { //If new pass back extra data if needed.
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved.', 'id' => $this->Country->id));
                        }
                        //echo json_encode(array('success' => 0, 'msg' => 'Data Saved!', 'data' => $dt));
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Some errors occurred.'));
                    }

                    break;

                case 'delete':
                    $ids = $_POST['ids'];
                    $modObj = ClassRegistry::init('Country');
                    $result = $modObj->updateAll(
                        $this->sanitize(array('Country.deleted' => "'y'")),
                        $this->sanitize(array('Country.id' => $ids))
                    );
                    if ($result) {
                        echo json_encode(array('code' => 0, 'msg' => 'Data Deleted!'));
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Data cannot be deleted'));
                    }
                    break;
            }
        }

        $page_title = 'Supported Countries';
        $page_summary = 'Manage your users supported countries';
        $page_icon = 'iconfa-globe';

        $controller = $this;
        $this->set(compact('page_title', 'page_summary', 'page_icon', 'controller', 'permissions'));

    }


    function country_operators($type = 'get'){
        $authUser = $this->Auth->user();
        $permissions = $this->action_permission;
        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;

            switch ($type) {
                case 'get' :
                    /**  Get posted data */
                    $page = isset($_POST['page']) ? $_POST['page'] : 1;
                    /** The current page */
                    $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
                    /** Sort column */
                    $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
                    /** Sort order */
                    $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
                    /** Search column */
                    $search_query = isset($_POST['query']) ? $_POST['query'] : '';
                    /** Search string */
                    /** @var Filters  */
                    $filter_country =   isset($_POST['filter_country']) ? $_POST['filter_country'] : -1 ;

                    $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
                    $limit = $rp;
                    $start = ($page - 1) * $rp;


                    $condition_array = array(
                        'CountryOperator.deleted' => 'n'
                    );
                    if($filter_country != -1){
                        $condition_array["CountryOperator.country_id"] = $filter_country ;
                    }
                    if (!empty($search_query)) {
                        if ($qtype == 'operator') {
                            $condition_array["CountryOperator.$qtype LIKE"] = $search_query . '%';
                        }
                        else {
                            $condition_array["CountryOperator.".$qtype] = $search_query ;
                        }
                    }
                    $contain = array('Country'=>array('fields'=>array('Country.id','Country.name')));
                    $data_table = $this->CountryOperator->find('all', array('conditions' => $condition_array, 'contain'=>$contain, 'order' => "CountryOperator.$sortname $sortorder", 'limit' => $start . ',' . $limit, 'recursive' => 1));
                    $data_table_count = $this->CountryOperator->find('count', array('conditions' => $condition_array, 'recursive' => -1));

                    $total_records = $data_table_count;

                    if ($data_table) {
                        $return_arr = array();
                        foreach ($data_table as $obj) {
                            $return_arr[] = array(
                                'id' => $obj['CountryOperator']['id'],
                                'cell' => array(
                                    $obj['CountryOperator']['id'],
                                    $obj['CountryOperator']['operator'],
                                    $obj['Country']['name']
                                )
                            );
                        }
                        return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
                    }
                    else {
                        return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
                    }
                    break;

                case 'save' :
                    $data = $_POST;
                    if ($data['id'] == 0) {//Mew
                        if(!in_array('A',$permissions)){
                            return json_encode(array('code' => 1, 'msg' => 'Access Denied.'));
                        }
                    }
                    else{
                        if(!in_array('E',$permissions)){
                            return json_encode(array('code' => 1, 'msg' => 'Access Denied.'));
                        }
                    }

                    if ($data['id'] > 0) {
                        $data['modified_by'] = $authUser['id'];
                    } else {
                        $data['created_by'] = $authUser['id'];
                    }
                    $data['user_id'] = $authUser['id'];

                    if ($this->CountryOperator->save($this->sanitize($data))) {
                        if($data['id'] > 0){
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved'));
                        }
                        else{ //If new pass back extra data if needed.
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved!', 'id'=>$this->CountryOperator->id));
                        }
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Some errors occurred.'));
                    }
                    break;

                case 'delete':
                    if(!in_array('D',$permissions)){
                        return json_encode(array('code' => 1, 'msg' => 'Access Denied.'));
                    }
                    $response = $this->CountryOperator->deleteCountryOperators($this->sanitize($_POST['ids']));
                    if($response){
                        return json_encode(array('code' => 0, 'msg' => 'Country Operators deleted.'));
                    }
                    else{
                        return json_encode(array('code' => 1, 'msg' => 'Country Operators cannot be deleted.'));
                    }
                    break;
            }
        }

        $c_data = $this->Country->getCountryOptions();
        $country_opt = $c_data;
        $country_filter =  array_merge(array(0=>array('id'=>-1,'name'=>'All')),$c_data);

        $user_id = $authUser['id'];
        $page_title = 'Country Operators';
        $page_summary = 'Manage your country operators';
        $page_icon = 'iconfa-signal';
        $this->set(compact('page_title','page_summary','page_icon','permissions','user_id','country_opt','country_filter'));

    }



    function faqs($type = 'get')
    {
        $permissions = $this->action_permission;
        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;
            $authUser = $this->Auth->user();
            switch ($type) {
                case 'get' :
                    /**  Get posted data */
                    $page = isset($_POST['page']) ? $_POST['page'] : 1;
                    /** The current page */
                    $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
                    /** Sort column */
                    $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
                    /** Sort order */
                    $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
                    /** Search column */
                    $search_query = isset($_POST['query']) ? $_POST['query'] : '';
                    /** Search string */
                    $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
                    $limit = $rp;
                    $start = ($page - 1) * $rp;

                    $condition_array = array('Faq.deleted' => 'n');

                    if (!empty($search_query)) {
                        if ($qtype == 'name') {
                            $condition_array['Faq.question LIKE'] = $search_query . '%';
                        } else {
                            /* $condition_array = array(
                                 "User.$qtype LIKE" => $search_query . '%',
                                 'User.deleted' => 'n'
                             );*/
                        }
                    }
                    // $fields = array('User.id', 'User.username', 'User.first_name', 'User.last_name', 'User.group_id', 'User.active');
                    $data_table = $this->Faq->find('all', array('conditions' => $condition_array, 'order' => "Faq.$sortname $sortorder", 'limit' => $start . ',' . $limit, 'recursive' => -1));
                    $data_table_count = $this->Faq->find('count', array('conditions' => $condition_array, 'recursive' => -1));

                    $total_records = $data_table_count;

                    if ($data_table) {
                        $return_arr = array();
                        foreach ($data_table as $obj) {
                            $return_arr[] = array(
                                'id' => $obj['Faq']['id'],
                                'cell' => array(
                                    $obj['Faq']['id'],
                                    $obj['Faq']['question'],
                                    $obj['Faq']['answer']
                                )
                            );
                        }
                        return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
                    } else {
                        return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
                    }

                    break;

                case 'save' :
                    if ($_POST['id'] == 0) { //Mew
                        if (!in_array('A', $permissions)) {
                            return json_encode(array('code' => 1, 'msg' => 'Access Denied.'));
                        }
                    } else {
                        if (!in_array('E', $permissions)) {
                            return json_encode(array('code' => 1, 'msg' => 'Access Denied.'));
                        }
                    }
                    $data = array('Faq' => $_POST);
                    $data['Faq']['modified_by'] = $this->Auth->user('id');
                    if ($_POST['id'] == 0) {
                        $data['Faq']['created_by'] = $this->Auth->user('id');
                    }

                    if ($this->Faq->save($this->sanitize($data))) {
                        if ($_POST['id'] > 0) {
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved'));
                        } else { //If new pass back extra data if needed.
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved.', 'id' => $this->Faq->id));
                        }
                        //echo json_encode(array('success' => 0, 'msg' => 'Data Saved!', 'data' => $dt));
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Some errors occurred.'));
                    }

                    break;

                case 'delete':
                    $ids = $_POST['ids'];
                    $modObj = ClassRegistry::init('Faq');
                    $result = $modObj->updateAll(
                        $this->sanitize(array('Faq.deleted' => "'y'")),
                        $this->sanitize(array('Faq.id' => $ids))
                    );
                    if ($result) {
                        echo json_encode(array('code' => 0, 'msg' => 'Data Deleted!'));
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Data cannot be deleted'));
                    }
                    break;
            }
        }

        $page_title = 'FAQs';
        $page_summary = 'Manage your FAQs';
        $page_icon = 'iconfa-question-sign';

        $controller = $this;
        $this->set(compact('page_title', 'page_summary', 'page_icon', 'controller', 'permissions'));

    }


}